import pandas as pd
import pandas_datareader.data as web
from datetime import datetime, timedelta

# Define the start and end date for the data retrieval
start_date = '2015-01-01'
end_date = '2025-01-01'

def fetch_stock_data(symbol, start_date, end_date):
    """
    Fetch daily stock data for a given symbol from Stooq
    """
    try:
        data = web.DataReader(symbol, 'stooq', start=start_date, end=end_date)
        # Reset index to make date a column
        data = data.reset_index()
        # Add symbol column
        data['symbol'] = symbol
        # Rename columns to match required format
        data = data.rename(columns={
            'Date': 'date',
            'Open': 'open',
            'Close': 'close',
            'High': 'high',
            'Low': 'low',
            'Volume': 'volume'
        })
        # Reorder columns
        data = data[['symbol', 'date', 'open', 'close', 'high', 'low', 'volume']]
        return data
    except Exception as e:
        print(f"Error fetching data for {symbol}: {e}")
        return None

# Fetch data for QQQ
print("Fetching QQQ data...")
qqq_data = fetch_stock_data('QQQ', start_date, end_date)

# Fetch data for TQQQ
print("Fetching TQQQ data...")
tqqq_data = fetch_stock_data('TQQQ', start_date, end_date)

# Save to CSV files
if qqq_data is not None:
    qqq_data.to_csv('QQQ_daily_prices_2015_2025.csv', index=False)
    print("QQQ data saved to QQQ_daily_prices_2015_2025.csv")
    print(f"QQQ records: {len(qqq_data)}")

if tqqq_data is not None:
    tqqq_data.to_csv('TQQQ_daily_prices_2015_2025.csv', index=False)
    print("TQQQ data saved to TQQQ_daily_prices_2015_2025.csv")
    print(f"TQQQ records: {len(tqqq_data)}")

# Display the first few rows of each dataframe
if qqq_data is not None:
    print("\nQQQ data sample:")
    print(qqq_data.head())

if tqqq_data is not None:
    print("\nTQQQ data sample:")
    print(tqqq_data.head())
